/**
 * 功能：在当前页面上玩俄罗斯方块
 * 作者：konger123（https://gitee.com/konger123）
 */
/*
=============================================================================================
免责声明：
	以下游戏的核心代码来源于网络，本人只是做了修改和补充，在此仅供学习研究使用。
	因使用此代码带来的法律责任本人概不负责！敬请知悉！
=============================================================================================
*/

//如果没有创建过eros_gameboard则创建一下，并且初始化方法和变量
if(typeof eros_gameboard ==='undefined' || eros_gameboard == null) {
	//创建游戏界面
	var eros_gameboard = document.createElement('div');
	eros_gameboard.id = 'eros_gameboard';
	eros_gameboard.style = 'position:fixed;left:0;top:0;width:500px;height:600px;background:#000;font:25px/25px 宋体;';
	eros_gameboard.innerHTML = '<div id="eros_box" style="float:left;width:252px;height:550px;border:#999 20px ridge;color:#9f9;text-shadow:2px 3px 1px #0f0;"></div><div id="eros_info" style="float:left;color:#cfc;padding:24px;">NEXT:<div id="eros_next" style="padding:8px;width:105px;color:#9f9;text-shadow:2px 3px 1px #0f0;"></div><div id="eros_text"></div><div id="eros_help" style="font-size:14px;color:darkorange;padding:10px 0;">键盘控制说明：<br>上&emsp;&emsp;旋转<br>下&emsp;&emsp;快下<Br>左&emsp;&emsp;左移<br>右&emsp;&emsp;右移<br>空格&emsp;暂停/继续</div><div id="eros_toolbar"><button id="startBtn" onclick="restart();">重新开始</button><button id="closeBtn" onclick="closeGame();">关闭游戏</button></div></div>';
	document.body.appendChild(eros_gameboard);
	
	///////////////////////////////////////////////////////////////////////
	
	//初始化游戏变量及方法（）
	var map=eval('['+Array(23).join('0x801,')+'0xfff]');
	var tatris=[[0x6600],[0x2222,0xf00],[0xc600,0x2640],[0x6c00,0x4620],[0x4460,0x2e0,0x6220,0x740],[0x2260,0xe20,0x6440,0x4700],[0x2620,0x720,0x2320,0x2700]];
	var char={x:'\u3000',s:'\u25a0',t:'\u25a1'};
	var keycom={'38':'rotate(1)','40':'down()','37':'move(2,1)','39':'move(0.5,-1)','32':'0;pause=!pause'};
	var dia, pos, bak, run, next, pause=false, info={speed:1,lines:0,score:0};
	function start(){
		dia=next.d;
		bak=pos={fk:[],y:0,x:4,s:next.s};
		nextdia();
		document.getElementById('eros_next').innerHTML=(next.d[next.s%next.d.length]|0x10000).toString(2).slice(-16).replace(/..../g,'$&<br/>').replace(/1/g,char.t).replace(/0/g,char.x);
		document.getElementById('eros_text').innerHTML='SCORE:'+info.score+'<br/><br/>LINES:'+info.lines+'<br/><br/>SPEED:'+info.speed;
		rotate(0);
		run=setInterval('pause||down()',~~(Math.pow(1.3,12-info.speed)*30+20));
	}
	function over(){
		document.onkeydown=null;
		document.getElementById('eros_text').innerHTML='SCORE:'+info.score+'<br/><br/>LINES:'+info.lines+'<br/><br/>SPEED:'+info.speed+'<br/><br/>GAME OVER!';
		//alert('GAME OVER');
	}
	function nextdia(){
		next={d:tatris[~~(Math.random()*7)],s:~~(Math.random()*4)};
	}
	function update(t){
		bak={fk:pos.fk.slice(0),y:pos.y,x:pos.x,s:pos.s};
		if(t) return;
		for(var i=0,a2=''; i<22; i++)
			a2+=map[i].toString(2).slice(1,-1)+'<br/>';
		for(var i=0,n; i<4; i++)
			if(/([^0]+)/.test(bak.fk[i].toString(2).replace(/1/g,char.t)))
				a2=a2.substr(0,n=(bak.y+i+1)*15-RegExp.$_.length-4)+RegExp.$1+a2.slice(n+RegExp.$1.length);
		document.getElementById('eros_box').innerHTML=a2.replace(/1/g,char.s).replace(/0/g,char.x);
	}
	function is(){
		for(var i=0; i<4; i++)
			if((pos.fk[i]&map[pos.y+i])!=0) return pos=bak;
	}
	function rotate(r){
		var f=dia[pos.s=(pos.s+r)%dia.length];
		for(var i=0; i<4; i++)
			pos.fk[i]=(f>>(12-i*4)&15)<<pos.x;
		update(is());
	}
	function down(){
		++pos.y;
		if(is()){
			for(var i=0, r=0; i<4 && pos.y+i<22; i++)
				if((map[pos.y+i]|=pos.fk[i])==0xfff){
					map.splice(pos.y+i,1), map.unshift(0x801);
					++info.lines%20==0 && info.speed++, r++;
				}
			if(run != null) {
				clearInterval(run);
				run = null;
			}
			if(map[1]!=0x801) return over();
			info.score+=~~(Math.pow(r,1.5)*10)+2;
			start();
		}
		update();
	}
	function move(t,k){
		pos.x+=k;
		for(var i=0; i<4; i++)
			pos.fk[i]*=t;
		update(is());
	}
	//禁止body滚动
	function disableScroll(){
		document.body.overflow_old = document.body.style.overflow;
		//隐藏body滚动条
		document.body.style.overflow='hidden';
	}
	//恢复body滚动
	function enableScroll(){
		//恢复body滚动条
		document.body.style.overflow = document.body.overflow_old;
	}
	function restart(){
		if(run != null) {
			clearInterval(run);
			run = null;
		}
		map = eval('['+Array(23).join('0x801,')+'0xfff]');
		info = {speed:1,lines:0,score:0};
		dia = pos = bak = run = next = null;
		pause = false;
		document.getElementById('eros_box').innerHTML='';
		
		document.onkeydown=function(e){
			eval('pause||'+keycom[(e?e:event).keyCode]);
		};
		
		disableScroll();
		
		nextdia();
		start();
	}
	//关闭游戏
	function closeGame() {
		//恢复body滚动
		enableScroll();
		if(run != null) {
			clearInterval(run);
			run = null;
		}
		eros_gameboard = map = tatris = char = keycom = dia = pos = bak = run = next = pause = info = null;
		document.getElementById('eros_box').innerHTML='';
		//事件销毁
		document.onkeydown = null;
		//方法销毁
		start = over = nextdia = update = is = rotate = down = move = disableScroll = enableScroll = restart;
		//销毁容器
		document.querySelector('#eros_gameboard').remove();
	}
	
	//启动游戏
	restart();
} else {
	//重启游戏
	restart();
}